<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Part.1.E.3.controlflow</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
</head>

<body id="index" class="home">
        <header id="banner" class="body">
                <h1><a href="/">PythonTutorials </a></h1>
                <nav><ul>
                    <li><a href="/category/cpp.html">cpp</a></li>
                    <li class="active"><a href="/category/python.html">python</a></li>
                </ul>
                </nav>
        </header><!-- /#banner -->
<section id="content" class="body">
  <article>
    <header>
      <h1 class="entry-title">
        <a href="/Part.1.E.3.controlflow.html" rel="bookmark"
           title="Permalink to Part.1.E.3.controlflow">Part.1.E.3.controlflow</a></h1>
    </header>

    <div class="entry-content">
<footer class="post-info">
        <span>Mon 06 April 2020</span>
<span>| tags: <a href="/tag/python.html">python</a><a href="/tag/progarmming.html">progarmming</a><a href="/tag/excel.html">Excel</a></span>
</footer><!-- /.post-info -->      <h1>流程控制</h1>
<p>在相对深入了解了值的基本操作之后，我们需要再返回来对流程控制做更深入的了解。</p>
<p>之前我们看过这个寻找质数的程序：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
        <span class="k">continue</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">break</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>


<p>这其中，包含了<em>分支</em>与<em>循环</em> —— 无论多复杂的流程控制用这两个东西就够了，就好像无论多复杂的电路最终都是由通路和开路仅仅两个状态构成的一样。</p>
<blockquote>
<p>今天的人们觉得这是 “天经地义” 的事情，可实际上并非如此。这是 1966 年的一篇论文所带来的巨大改变 —— <em>Flow diagrams, turing machines and languages with only two formation rules</em> by Böhm and Jacopini (1966)。实际上，直到上个世纪末，<code>GOTO</code> 语句才从各种语言里近乎 “灭绝”……</p>
<p>任何进步，无论大小，其实都相当不容易，都非常耗时费力 —— 在哪儿都一样。有兴趣、有时间，可以去浏览 Wikipedia 上的简要说明 —— <a href="https://en.wikipedia.org/wiki/Control_flow#Goto">Wikipedia: Minimal structured control flow</a>。</p>
</blockquote>
<h2>if 语句</h2>
<p><code>if</code> 语句的最简单构成是这样 —— 注意第 1 行末尾的冒号 <code>:</code> 和第 2 行的缩进：</p>
<div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">expression</span><span class="p">:</span>
    <span class="n">statements</span>
</pre></div>


<p>如果表达式 <code>expression</code> 返回值为真，执行 <code>if</code> 语句块内部的 <code>statements</code>，否则，什么都不做，执行 <code>if</code> 之后的下一个语句。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>

<span class="k">if</span> <span class="n">r</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{r} is even.&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>372 is even.
</pre></div>


<p>如果，表达式 <code>expression</code> 返回值无论真假，我们都需要做一点相应的事情，那么我们这么写：</p>
<div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">expression</span><span class="p">:</span>
    <span class="n">statements_for_True</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">statements_for_False</span>
</pre></div>


<p>如果表达式 <code>expression</code> 返回值为真，执行 <code>if</code> 语句块内部的 <code>statements_for_True</code>，否则，就执行 <code>else</code> 语句块内部的 <code>statements_for_False</code></p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>

<span class="k">if</span> <span class="n">r</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{r} is even.&#39;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;{r} is odd.&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>945 is odd.
</pre></div>


<p>有时，表达式 <code>&lt;expression&gt;</code> 返回的值有多种情况，并且针对不同的情况我们都要做相应的事情，那么可以这么写：</p>
<div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">expression_1</span><span class="p">:</span>
    <span class="n">statements_for_expression_1_True</span>

<span class="k">elif</span> <span class="n">expression_2</span><span class="p">:</span>
    <span class="n">statements_for_expression_2_True</span>

<span class="k">elif</span> <span class="n">expression_3</span><span class="p">:</span>
    <span class="n">statements_for_expression_3_True</span>

<span class="k">elif</span> <span class="n">expression_</span><span class="o">...</span><span class="p">:</span>
    <span class="n">statements_for_expression_</span><span class="o">...</span><span class="n">_True</span>
</pre></div>


<p>Python 用 <code>elif</code> 处理这种多情况分支，相当于其它编程语言中使用 <code>switch</code> 或者 <code>case</code>……</p>
<p><code>elif</code> 是 <code>else if</code> 的缩写，作用相同。</p>
<p>以下程序模拟投两个骰子的结果 —— 两个骰子数字加起来，等于 <code>7</code> 算平，大于 <code>7</code> 算大，小于 <code>7</code> 算小：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">13</span><span class="p">)</span>

<span class="k">if</span> <span class="n">r</span> <span class="o">==</span> <span class="mi">7</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Draw!&#39;</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">r</span> <span class="o">&lt;</span> <span class="mi">7</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Small!&#39;</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">r</span> <span class="o">&gt;</span> <span class="mi">7</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Big!&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>Big!
</pre></div>


<p>当然你还可以模拟投飞了的情况，即，最终的骰子数是 <code>0</code> 或者 <code>1</code>，即，<code>&lt; 2</code>：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">13</span><span class="p">)</span> <span class="c1"># 生成的随机数应该从 0 开始了；</span>

<span class="k">if</span> <span class="n">r</span> <span class="o">==</span> <span class="mi">7</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Draw!&#39;</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">r</span> <span class="o">&gt;=</span> <span class="mi">2</span> <span class="ow">and</span> <span class="n">r</span> <span class="o">&lt;</span> <span class="mi">7</span><span class="p">:</span>      <span class="c1"># 如果这里直接写 elif r &lt; 7:，那么，else: 那一部分永远不会被执行……</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Small!&#39;</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">r</span> <span class="o">&gt;</span> <span class="mi">7</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Big!&#39;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Not valid!&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>Small!
</pre></div>


<h2>for 循环</h2>
<p>Python 语言中，<code>for</code> 循环不使用其它语言中那样的计数器，取而代之的是 <code>range()</code> 这个我称其为 “整数等差数列生成器” 的函数。</p>
<p>用 C 语言写循环是这样的：</p>
<div class="highlight"><pre><span></span><span class="k">for</span><span class="p">(</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">a</span> <span class="o">=</span> <span class="n">a</span> <span class="o">+</span> <span class="mi">1</span> <span class="p">){</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">&quot;value of a: %d</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>


<p>用 Python 写同样的东西，是这样的：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;value of a: {a}&#39;</span><span class="p">)</span> <span class="c1">#每次 a 的值都不同，从 0 递增至 9</span>
</pre></div>


<div class="highlight"><pre><span></span>value of a: 0
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
</pre></div>


<h3>range() 函数</h3>
<p><code>range()</code> 是个内建函数，<a href="https://docs.python.org/3/library/functions.html#func-range">它的文档</a>是这样写的：</p>
<blockquote>
<p><strong>range</strong>(<em>stop</em>)</p>
<p><strong>range</strong>(<em>start, stop[, step]</em>)</p>
</blockquote>
<p>只有一个参数的时候，这个参数被理解为 <code>stop</code>，生成一个从 <code>0</code> 开始，到 <code>stop - 1</code> 的整数数列。</p>
<p>这就解释了为什么有的时候我们会在 <code>for ... in range(...):</code> 这种循环内的语句块里进行计算的时候，经常会在变量之后写上 <code>+ 1</code>，因为我们 range(n) 的返回数列中不包含 <code>n</code>，但我们有时候却需要 <code>n</code>。<a href="Part.1.E.1.entrance.ipynb#plusone">点击这里返回看看第一章里提到的例子：所谓算法那一小节</a>。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span> <span class="c1"># 将 range(10) 转换成 list，以便清楚看到其内容。</span>
</pre></div>


<div class="highlight"><pre><span></span>range(0, 10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre></div>


<p><code>start</code> 参数的默认值是 <code>0</code>。如需指定起点，那么得给 <code>range()</code> 传递两个参数，比如，<code>range(2, 13)</code>……</p>
<div class="highlight"><pre><span></span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">13</span><span class="p">))</span>
</pre></div>


<div class="highlight"><pre><span></span>[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</pre></div>


<p>第三个参数可选；<code>step</code>，步长，就相当于是 “等差数列” 当中的 “差”，默认值是 <code>1</code>。例如，<code>range(1, 10, 2)</code> 生成的是这样一个数列 <code>[1, 3, 5, 7, 9]</code>。所以，打印 <code>0 ～ 10</code> 之间的所有奇数，可以这样写：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">2</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>1
3
5
7
9
</pre></div>


<p>我们也可以生成负数的数列：</p>
<div class="highlight"><pre><span></span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>
</pre></div>


<div class="highlight"><pre><span></span>[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
</pre></div>


<h3>Continue、Break 和 Pass</h3>
<p>在循环的过程中，还可以用 <code>continue</code> 和 <code>break</code> 控制流程走向，通常是在某条件判断发生的情况下 —— 正如你早就见过的那样：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
        <span class="k">continue</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">break</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>


<p><code>continue</code> 语句将忽略其后的语句开始下次循环，而 <code>break</code> 语句将从此结束当前循环，开始执行循环之后的语句：</p>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/continue-break.png?raw=true"></p>
<p><code>for</code> 语句块还可以附加一个 <code>else</code> —— 这是 Python 的一个比较有个性的地方。附加在 <code>for</code> 结尾的 <code>else</code> 语句块，<em>在没有 <code>break</code> 发生的情况下会运行</em>。</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
        <span class="k">continue</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">break</span>
    <span class="k">else</span><span class="p">:</span>               <span class="c1"># 下一行的 print(n) 事实上属于语句块 for i in range(2, n):</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>        <span class="c1"># 整个循环结束，都没有发生 break 的情况下，才执行一次 print(n)</span>
</pre></div>


<div class="highlight"><pre><span></span>2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
</pre></div>


<p>试比较以下两段代码：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
        <span class="k">continue</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">break</span>
    <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>            <span class="c1"># 事实上相当于针对 range(2, 100) 中每个 n 都执行了一次 print(n)</span>
                        <span class="c1"># 这个 print(n) 属于语句块 for n in range(2, 100):</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
        <span class="k">continue</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">break</span>
        <span class="k">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>            <span class="c1"># 事实上相当于针对 range(2, n) 中每个 i 都执行了一次 print(n)</span>
</pre></div>


<div class="highlight"><pre><span></span>2
3
5
5
5
7
7
7
7
7
9
11
11
11
...
97
97
97
97
99
</pre></div>


<p><code>pass</code> 语句什么都不干：</p>
<p>再比如，</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">someFunction</span><span class="p">():</span>
    <span class="k">pass</span>
</pre></div>


<p>又或者：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">):</span>
    <span class="k">pass</span>
    <span class="k">if</span> <span class="n">i</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">pass</span>
</pre></div>


<p>换个角度去理解的话可能更清楚：<code>pass</code> 这个语句更多是给写程序的人用的。当你写程序的时候，你可以用 <code>pass</code> 占位，而后先写别的部分，过后再回来补充本来应该写在 <code>pass</code> 所在位置的那一段代码。</p>
<p>写嵌套的判断语句或循环语句的时候，最常用 <code>pass</code>，因为写嵌套挺费脑子的，一不小心就弄乱了。所以，经常需要先用 <code>pass</code> 占位，而后逐一突破。</p>
<h2>while 循环</h2>
<p>今天，在绝大多数编程语言中，都提供两种循环结构：</p>
<blockquote>
<ul>
<li>Collection-controlled loops（以集合为基础的循环）</li>
<li>Condition-controlled loops（以条件为基础的循环）</li>
</ul>
</blockquote>
<p>之前的 <code>for ... in ...</code> 就是 Collection-controlled loops；而在 Python 中提供的 Condition-controlled loops 是 <code>while</code> 循环。</p>
<p><code>while</code> 循环的格式如下：</p>
<div class="highlight"><pre><span></span><span class="k">while</span> <span class="n">expression</span><span class="p">:</span>
    <span class="n">statements</span>
</pre></div>


<p>输出 1000 以内的斐波那契数列的程序如下：</p>
<div class="highlight"><pre><span></span><span class="n">n</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="k">print</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
</pre></div>


<p><code>for</code> 和 <code>while</code> 的区别在哪里？什么时候应该用哪个？</p>
<p><code>for</code> 更适合处理序列类型的数据（Sequence Type）的迭代，比如处理字符串中的每一个字符，比如把 <code>range()</code> 返回的数列当作某种序列类型的索引。</p>
<p><code>while</code> 更为灵活，因为它后面只需要接上一个逻辑表达式即可。</p>
<h2>一个投骰子赌大小的游戏</h2>
<p>虽然还不可能随心所欲写程序，但是，你现在具备了起码的 “阅读能力”。有了以上大概的介绍，你也许可以读懂一些代码了 —— 它们在你眼里再也不是天书了……</p>
<p>以下是一个让用户和程序玩掷骰子赌大小的程序。规则如下：</p>
<blockquote>
<ul>
<li>每次计算机随机生成一个 <code>2... 12</code> 之间的整数，用来模拟机器人投两个骰子的情况；</li>
<li>机器人和用户的起始资金都是 10 个硬币</li>
<li>要求用户猜大小：<ul>
<li>用户输入 <code>b</code> 代表 “大”；</li>
<li>用户输入 <code>s</code> 代表 “小”；</li>
<li>用户输入 <code>q</code> 代表 “退出”；</li>
</ul>
</li>
<li>用户的输入和随机产生的数字比较有以下几种情况：<ul>
<li>随机数小于 <code>7</code>，用户猜小，用户赢；</li>
<li>随机数小于 <code>7</code>，用户猜大，用户输；</li>
<li>随机数等于 <code>7</code>，用户无论猜大还是猜小，结局平，不输不赢；</li>
<li>随机数大于 <code>7</code>，用户猜小，用户输；</li>
<li>随机数大于 <code>7</code>，用户猜大，用户赢；</li>
</ul>
</li>
<li>游戏结束条件：<ul>
<li>机器人和用户，若任意一方硬币数量为 <code>0</code>，则游戏结束；</li>
<li>用户输入了 <code>q</code> 主动终止游戏。</li>
</ul>
</li>
</ul>
</blockquote>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">randrange</span>

<span class="n">coin_user</span><span class="p">,</span> <span class="n">coin_bot</span> <span class="o">=</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">10</span> <span class="c1"># 可以用一个赋值符号分别为多个变量赋值</span>
<span class="n">rounds_of_game</span> <span class="o">=</span> <span class="mi">0</span>

<span class="k">def</span> <span class="nf">bet</span><span class="p">(</span><span class="n">dice</span><span class="p">,</span> <span class="n">wager</span><span class="p">):</span>    <span class="c1"># 接收两个参数，一个是骰子点数，另一个用户的输入</span>
    <span class="k">if</span> <span class="n">dice</span> <span class="o">==</span> <span class="mi">7</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;The dice is {dice};</span><span class="se">\n</span><span class="s1">DRAW!</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span> <span class="c1"># \n 是换行符号</span>
        <span class="k">return</span> <span class="mi">0</span>
    <span class="k">elif</span> <span class="n">dice</span> <span class="o">&lt;</span> <span class="mi">7</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">wager</span> <span class="o">==</span> <span class="s1">&#39;s&#39;</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;The dice is {dice};</span><span class="se">\n</span><span class="s1">You WIN!</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">return</span> <span class="mi">1</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;The dice is {dice};</span><span class="se">\n</span><span class="s1">You LOST!</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span>
    <span class="k">elif</span> <span class="n">dice</span> <span class="o">&gt;</span> <span class="mi">7</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">wager</span> <span class="o">==</span> <span class="s1">&#39;s&#39;</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;The dice is {dice};</span><span class="se">\n</span><span class="s1">You LOST!</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;The dice is {dice};</span><span class="se">\n</span><span class="s1">You WIN!</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">return</span> <span class="mi">1</span>

<span class="k">while</span> <span class="bp">True</span><span class="p">:</span>         <span class="c1">#  除 for 之外的另外一个循环语句</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;You: {coin_user}</span><span class="se">\t</span><span class="s1"> Bot: {coin_bot}&#39;</span><span class="p">)</span>
    <span class="n">dice</span> <span class="o">=</span> <span class="n">randrange</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">13</span><span class="p">)</span>   <span class="c1"># 生成一个 2 到 12 的随机数</span>
    <span class="n">wager</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s2">&quot;What&#39;s your bet? &quot;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">wager</span> <span class="o">==</span> <span class="s1">&#39;q&#39;</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="k">elif</span> <span class="n">wager</span> <span class="ow">in</span> <span class="s1">&#39;bs&#39;</span><span class="p">:</span>  <span class="c1"># 只有当用户输入的是 b 或者 s 得时候，才 “掷骰子”……</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">bet</span><span class="p">(</span><span class="n">dice</span><span class="p">,</span> <span class="n">wager</span><span class="p">)</span>
        <span class="n">coin_user</span> <span class="o">+=</span> <span class="n">result</span>    <span class="c1"># coin_user += result 相当于 coin_user = coin_user + result</span>
        <span class="n">coin_bot</span> <span class="o">-=</span> <span class="n">result</span>
        <span class="n">rounds_of_game</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="k">if</span> <span class="n">coin_user</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s2">&quot;Woops, you&#39;ve LOST ALL, and game over!&quot;</span><span class="p">)</span>
        <span class="k">break</span>
    <span class="k">elif</span> <span class="n">coin_bot</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s2">&quot;Woops, the robot&#39;s LOST ALL, and game over!&quot;</span><span class="p">)</span>
        <span class="k">break</span>

<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s2">&quot;You&#39;ve played {rounds_of_game} rounds.</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s2">&quot;You have {coin_user} coins now.</span><span class="se">\n</span><span class="s2">Bye!&quot;</span><span class="p">)</span>
</pre></div>


<h2>总结</h2>
<p>有控制流，才能算得上是程序。</p>
<blockquote>
<ul>
<li>只处理一种情况，用 <code>if ...</code></li>
<li>处理 <code>True</code>/<code>False</code> 两种情况，用 <code>if ... else ...</code></li>
<li>处理多种情况，用 <code>if ... elif ... elif ... else ...</code></li>
<li>迭代有序数据类型，用 <code>for ... in ...</code>，如果需要处理没有 <code>break</code> 发生的情况，用 <code>for ... else ...</code></li>
<li>其它循环，用 <code>while ...</code></li>
<li>与循环相关的语句还有 <code>continue</code>、<code>break</code>、<code>pass</code></li>
<li>函数从控制流角度去看其实就是子程序</li>
</ul>
</blockquote>
    </div><!-- /.entry-content -->

  </article>
</section>
        <section id="extras" class="body">
                <div class="blogroll">
                        <h2>blogroll</h2>
                        <ul>
                            <li><a href="http://getpelican.com/">Pelican</a></li>
                            <li><a href="http://python.org/">Python.org</a></li>
                            <li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
                            <li><a href="#">You can modify those links in your config file</a></li>
                        </ul>
                </div><!-- /.blogroll -->
                <div class="social">
                        <h2>social</h2>
                        <ul>

                            <li><a href="#">You can add links in your config file</a></li>
                            <li><a href="#">Another social link</a></li>
                        </ul>
                </div><!-- /.social -->
        </section><!-- /#extras -->

        <footer id="contentinfo" class="body">
                <p>Powered by <a href="http://www.maxiaoan.com/">Maxiaoan</a></p>
        </footer><!-- /#contentinfo -->

</body>
</html>